package ioc

import (
	intrv1 "booksmart/book/api/proto/gen/intr/v1"
	"booksmart/book/interactive/service"
	"booksmart/book/internal/web/client"
	_ "booksmart/book/pkg/grpcx/balance"
	"booksmart/book/pkg/grpcx/registry/nacos"
	"github.com/fsnotify/fsnotify"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/resolver"
)

func InitNacosBuilder(client naming_client.INamingClient) *nacos.NacosBuilder {
	return &nacos.NacosBuilder{Client: client, ServiceName: "interactives"}

}

func InitIntrGRPCClientByNacos(builder *nacos.NacosBuilder) intrv1.InteractiveServiceClient {
	type Config struct {
		Addr      string
		Secure    bool
		Threshold int32
	}
	var cfg Config
	err1 := viper.UnmarshalKey("grpc.client.intr", &cfg)
	if err1 != nil {
		panic(err1)
	}
	var opts []grpc.DialOption
	if cfg.Secure {
		//启动HTTPS
	} else {
		opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	}
	resolver.Register(builder)
	var config = `{"loadBalancingConfig": [{"custom_wrr":{}}]}`
	opts = append(opts, grpc.WithDefaultServiceConfig(config))
	cc, err := grpc.Dial("nacos:///"+builder.ServiceName, opts...)
	if err != nil {
		panic(err)
	}
	remote := intrv1.NewInteractiveServiceClient(cc)
	return remote
}

func InitIntrGRPCClient(svc service.InteractiveService) intrv1.InteractiveServiceClient {
	type Config struct {
		Addr      string
		Secure    bool
		Threshold int32
	}
	var cfg Config
	err1 := viper.UnmarshalKey("grpc.client.intr", &cfg)
	if err1 != nil {
		panic(err1)
	}
	var opts []grpc.DialOption
	if cfg.Secure {
		//启动HTTPS
	} else {
		opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	}
	cc, err := grpc.Dial(cfg.Addr, opts...)
	if err != nil {
		panic(err)
	}
	local := client.NewInteractiveServiceAdapter(svc)
	remote := intrv1.NewInteractiveServiceClient(cc)
	res := client.NewGreyScaleInteractiveServiceClient(remote, local)
	viper.OnConfigChange(func(e fsnotify.Event) {
		var cfg Config
		errs := viper.UnmarshalKey("grpc.client.intr", &cfg)
		if errs != nil {
			//在这里输入日志
		}
		res.UpdateThreshold(cfg.Threshold)
	})
	return res
}
